import sys
from sys import argv

from kubernetes import config, client


# 参考
# https://v1-9.docs.kubernetes.io/docs/reference/generated/kubernetes-api/v1.9/#deploymentlist-v1beta1-extensions
# https://github.com/kubernetes-client/python/blob/master/examples/deployment_examples.py
#
def create_deployment_object(container_name, image):
    return client.V1Deployment(
        spec=client.ExtensionsV1beta1DeploymentSpec(
            template=client.V1PodTemplateSpec(
                spec=client.V1PodSpec(
                    containers=[
                        client.V1Container(name=container_name, image=image)
                    ]
                )
            )
        )
    )


def main():
    if len(argv) < 3:
        print("argv's len is less 2.", argv)
        sys.exit("args error")
    deploy_name = argv[1]
    version = argv[2]

    config.load_kube_config("/admin.yaml")

    image = "harbor.corp.hongen.com/hongen/" + deploy_name + ":" + version

    deployment = create_deployment_object(deploy_name, image)

    api = client.AppsV1Api()
    res = None
    try:
        res = api.patch_namespaced_deployment(name=deploy_name, namespace="default", body=deployment)
    except client.rest.ApiException as e:
        print("error :", e.body)
        sys.exit(e.status)
    else:
        print("ok:", res.spec.template.spec.containers[0].image)


if __name__ == '__main__':
    main()
